package com.br4mmie.asciistory.map;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

import com.br4mmie.asciistory.CharImage;
import com.br4mmie.asciistory.Restorable;


/**
 * Avatar MapObject so the player can be displayed on the map
 * @author Niels Schoemaker
 * 		   Bram Buurlage
 */
public class PlayerAvatar extends MapObject implements Restorable{

	private Map map;
	public PlayerAvatar(Map map)
	{
		super();
		super.image = new CharImage(1,1);
		image.fill('8');
		
		this.map = map;
	}
	
	/**
	 * moves the player on the map
	 * @param dX the amount to move to the right
	 * @param dY the amount to move downwards
	 */
	public void move(int dX, int dY)
	{
		int oldX = locX;
		int oldY = locY;
		
		super.move(dX, dY);
		if (map.getCollision(locX, locY))
		{
			locX = oldX;
			locY = oldY;
		}
	}
	
	/**
	 * sets the Map this PlayerAvatar is on
	 * @param map a Map.
	 */
	public void setMap(Map map)
	{
		this.map = map;
	}
	
	/**
	 * restore avatar from savefile
	 * @param reader savefile reader
	 * @param map the map to place the restored avatar on
	 * @return the restored PlayerAvatar
	 */
	public static PlayerAvatar restore(BufferedReader reader, Map map)
	{
		try 
		{
			PlayerAvatar avatar = new PlayerAvatar(map);
			avatar.locX = Integer.parseInt(reader.readLine().substring(2));
			avatar.locY = Integer.parseInt(reader.readLine().substring(2));
			reader.readLine();
			return avatar;
		} catch (IOException e) 
		{
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * save to writer
	 */
	public void save(BufferedWriter writer) 
	{
		try 
		{
			writer.write("avatar\n");
			writer.write("x "+locX+"\n");
			writer.write("y "+locY+"\n");
			writer.write("end\n");
		} catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}
